package org.lagou.edu.controller;

import org.lagou.edu.controller.assmebler.ShopAssembler;
import org.lagou.edu.controller.dto.ShopDTO;
import org.lagou.edu.controller.dto.ShopInfo;
import org.lagou.edu.service.ShopService;
import org.lagou.edu.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

/**
 * @author: oliver
 * @data: 2022/7/16 23:11
 **/
@RestController
@RequestMapping("/api/v1/shop")
public class ShopController {

    private static final ExecutorService EXECUTOR_GET_SHOP_THREAD_POOL = new ThreadPoolExecutor(10, 20, 10L,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000), new ThreadPoolExecutor.AbortPolicy());

    @Autowired
    private StockService stockService;

    @Autowired
    private ShopService shopService;

    /**
     * 查看商品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ShopDTO getShopInfo(@PathVariable Long id) {
        // 查询基本信息
        CompletableFuture<ShopInfo> shopInfo = CompletableFuture.supplyAsync(()
                -> shopService.queryShop(id), EXECUTOR_GET_SHOP_THREAD_POOL);
        // 查询库存信息
        CompletableFuture<Long> stockInfo = CompletableFuture.supplyAsync(()
                -> stockService.queryStock(id), EXECUTOR_GET_SHOP_THREAD_POOL);
        /**
         * todo 其他相关查询。。。。。
         * 1. 商店信息
         * 2. 活动信息
         * .......
         */
        CompletableFuture.allOf(shopInfo, stockInfo);
        try {
            // 数据组装
            return ShopAssembler.assemblerToShopInfo(shopInfo.get(), stockInfo.get());
        } catch (Exception e) {
            System.out.println("getShopInfo error");
            return new ShopDTO();
        }
    }
}
